<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    /**
     * 回调处理：
     * */
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {
            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $pay_time = Db::name('order')->where(['order_sn' => $order_sn])->value('pay_time');

            if ($pay_time == 0) {
                Db::startTrans();
                try {
                    $this->doOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 开通服务订单支付成功处理业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['order_sn' => $order_sn])->find();

        $order_id = $order_info['id'];

        Db::startTrans();
        try {
            $data = [
                'pay_time' => time(),
                'status' => 3
            ];
            Db::name('order')->where(['id' => $order_id])->update($data);

            Db::commit();
        } catch (\Exception $e) {
            file_put_contents(RUNTIME_PATH . 'order.txt', $e->getMessage() . PHP_EOL, FILE_APPEND);
            Db::rollback();
        }
    }
}